<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>小萌神订餐网</title>
  <!-- 图标 -->
  <link rel="short icon" href="image/eat0.ico" />
  <link rel="stylesheet" href="css/body.css" />
</head>
<body>

<div id="app">

  <div class="head">
    小萌神订餐网
    <div class="right">
      <span class="showlogin" id="showlogin" @click="loginflag=!loginflag" v-if="!isLogin">登录</span>
      <span id="exitspan" v-if="isLogin" v-cloak>
        欢迎您：{{username}} <a @click.prevent="historyflag=!historyflag">历史</a> | <a href="" @click.prevent="logout()">退出</a>
      </span>
    </div>
  </div>
  <div class="content">
    <ul class="allfoods" id="allfoods">
      <li v-for="(item,index) in data">
        <h3 @click="showFood(item.fid)">{{item.fname}}</h3>
        <div :id=`fid_${item.fid}` class="fooddesc" v-show="item.status">
          <img :src=`image/${item.fphoto}` class="foodimg" />
          <article class="foodprice">
            <p>菜品描述：{{item.detail}}</p>
            <p class="normalprice">原价：￥{{item.normprice}}</p>
            <p class="realprice">特价：￥{{item.realprice}}</p>
            <p class="buybtn" @click="addCart(item.fid,1)">加入购物车</p>
            <p>赞{{item.praise}}<span v-if="isLogin"@click="clickPraise(item.fid,index)">点一个</span></p>
          </article>
        </div>
      </li>
    </ul>
    <div style="background-color: white;color: red">
      <a  @click.prevent="clickPage(  1)">第一页</a>
      <a  @click.prevent="clickPage( pagebean.pre)" :page-data="pagebean.pre">上一页 {{pagebean.pre}}</a>
      <a  @click.prevent="clickPage( pagebean.next)" :page-data="pagebean.next">下一页 {{pagebean.next}}</a>
      <a  @click.prevent="clickPage( pagebean.totalpages)" :page-data="pagebean.totalpages">最后一页 {{pagebean.totalpages}}</a>
      总共{{pagebean.total}}条记录/共分{{pagebean.totalpages}}页，
      每页{{pagebean.pagesize}}条，当前第{{pagebean.pageno}}页
      <br/>
      按<select id="sortby" v-model="pagebean.sortby">
      <option value="fid" selected>菜品编号</option>
      <option value="realprice">成交价格</option></select>
      <select id="sort" v-model="pagebean.sort">
        <option value="asc" selected>升序</option>
        <option value="desc">降序</option>
      </select>
    </select>
    </div>
  </div>
  <!--  <div class="look">浏览记录</div> -->
  <div class="shoppingcar">
    <div class="carbag" id="carbag" :class="{isShow:isHide==true, isHide:isHide==false}">
      <p>购物车<span id="del" @click="clearAll()">[清空]</span></p>
      <table id="bagcontent" cellpadding="0" cellspacing="0">
        <tr v-for="cartfood in cartfoods">
          <td>{{cartfood.food.fname}}</td>
          <td>
            <button @click="addCart(cartfood.food.fid,-1)">-</button>
            {{cartfood.num}}
            <button @click="addCart(cartfood.food.fid,1)">+</button>

          </td>
        </tr>

      </table>
    </div>
    <div class="carprice" @click="showCart()">￥{{cartprice}}</div>
    <div class="carinfo" v-if="cartfoods.length<=0">购物车是空的</div>
    <div class="carinfo" v-else @click="orderflag=!orderflag">立即下单</div>
  </div>
  <div class="footer">
    Copyright © 2016 Xiaomengsheng Incorporated Company. All rights reserved.
    <br />
    订餐，就上小萌神订餐网!
  </div>
  <div class="look" v-if="historyflag">
    <span @click="getHistory()">浏览记录（点击我刷新）</span>
    <hr/>
    <ul>
      <li v-for="item in reversehistory">{{item.fid}} - {{item.fname}}</li>
    </ul>
  </div>

  <div class="login" id="login" v-if="loginflag">
    <span id="unshow" @click="loginflag=false">X</span>
    <form name="myform">
      <table>
        <tr>
          <td class="labname"><label for="username">用户名：</label></td>
          <td><input type="text" name="username" placeholder="请输入用户名"
                     id="username" v-model="username" /></td>
        </tr>
        <tr>
          <td class="labname"><label for="pwd">密码：</label></td>
          <td><input type="password" name="pwd" placeholder="请输入密码"
                     id="pwd" v-model="pwd"/></td>
        </tr>
        <tr>
          <td class="labname"><label for="yzm">验证码：</label></td>
          <td><input type="text" name="yzm" placeholder="请输入验证码"
                     id="yzm" v-model="valcode"/></td>
          <td><img src="code.action" id="yzm_img" /></td>
        </tr>
      </table>
    </form>
    <input type="button" value="login" class="btn" id="btn" @click="login()"/>
  </div>

  <!-- 订单信息 -->
  <div class="login" id="myinfo" v-if="orderflag">
    <span id="unshowinfo"  @click="orderflag=!orderflag" >X</span>
    <form name="forminfo">
      <table>
        <tr>
          <td class="labname"><label for="address">送货地址:</label></td>
          <td><input name="address"  type="text" placeholder="请输入送货地址" id="address" v-model="orderInfo.adress" /></td>
        </tr>
        <tr>
          <td class="labname"><label for="tel">联系电话:</label></td>
          <td><input type="text"  id="tel" placeholder="请输入联系电话" name="tel" v-model="orderInfo.tel" /></td>
        </tr>
        <tr>
          <td class="labname"><label for="deliverytime">送货时间:</label></td>
          <td><input type="text"  name="deliverytime" id="deliverytime" placeholder="请输入送货时间（默认马上发货）" v-model="orderInfo.deliverytime"/></td>
        </tr>
        <tr>
          <td class="labname"><label for="ps">附言:</label></td>
          <td><input type="text" id="ps" placeholder="请输入附言" name="ps"  v-model="orderInfo.ps"/></td>
        </tr>
      </table>
    </form>
    <input type="button" value="提交" class="btn"  id="submit" @click="confirmOrder()">
  </div>

</div>

<!--  在网页里面引入javascript    jquery:DOM   大家注意顺序  -->
<script src="js/vue.js"></script>
<script src="js/axios.js"></script>
<script type="text/javascript">
  let vm=new Vue({
    el:"#app",
    data:{
      orderflag:false,     //送货地址div
      loginflag:false,      //登录管理
      isLogin:false,//记录当前用户的登录状态
      //登录时要用的参数
      username:'',
      pwd:'a',
      valcode:'',
      data:[],//显示菜品列表
      cartfoods:[],//这是购物车中的商品列表。
      cartprice:0.0,//这是总价
      isHide:false,
      history:[],//历史浏览记录
      historyflag:false,//历史记录显示的div

      //将订单的model数据包装成一个对象
      orderInfo:{
        adress:'湖南工学院',
        tel:'12345',
        deliverytime:'2020-10-1',
        ps:'块快'
      },
      pagebean:{
        pageno:1,
        pagesize:5,
        sortby:'fid',
        sort:'asc',
        total:0,
        totalpages:0,
        pre:1,
        next:2
      }
    },
    methods:{
      clickPraise:function (fid,index){
        var params=new URLSearchParams();
        params.append("fid",fid);
        axios.post('resfood.action?op=clickPraise',params).then(result=>{
          let jm=result.data;
          if (jm.code==1){
            //this.data[index].praise=jm.obj.praise;//这个是最新的点赞数
            var d=this.data[index];
            d.praise=jm.obj.praise;
            this.data.splice(index,1,d);
          }

        });
      },
      confirmOrder:function (){
        var params=new URLSearchParams(this.orderInfo);
        axios.post('custOp.action?op=confirmOrder',params).then(result=>{
          let jm=result.data;
          if (jm.code==1){
            alert("下单成功");
            this.cartfoods=[];
            this.cartprice=0;
            this.isHide=false;
            this.orderflag=false;
          }

        });
      },
      clearAll:function (){
        axios.post('resorder.action?op=clearAll').then(result=>{
          let jm=result.data;
          if (jm.code==1){
            this.cartfoods=[];
            this.cartprice=0;
            isHide=false;
          }

        });
      },
      showCart:function (){
        this.isHide=!this.isHide;
      },
      addCart:function (fid,num){
        //要添加购物车的话，先保证登录过
        if (this.username==null||this.username==''){
          alert("请登录");
          return;
        }
        var params=new URLSearchParams();
        params.append("num",num);
        params.append("fid",fid);
        axios.post('resorder.action?op=order',params).then(result=>{
          let jm=result.data;
          if (jm.code==-1){
           alert("请登录");
           return;
          }else if (jm.code==0){
            alert("添加购物车失败");
            return;
          }else {
            //TODO: 成功后显示购物车数据
            //jsonModel中是数组
            this.showCartInfo(jm.obj);

          }


        });


      },
      showCartInfo:function (cart){
        this.cartfoods=cart;
        //计算总价
        this.cartprice=0.0;
        this.cartfoods.forEach((item,index)=>{
          this.cartprice+=item.smallCount;
        });
      },
      showFood:function (fid){
        this.data.forEach((item,index)=>{
          item.status= fid==item.fid;
        });
        //数据埋点
        axios.post('resfood.action?op=traceBrowseFood&fid='+fid).then(result=>{
          let jm=result.data;
          if (jm.code==1){

          }


        });
      },
      logout:function (){
        axios.post('user.action?op=logout').then(result=>{
          let jm=result.data;
          if (jm.code==1){
           this.username='';
           this.pwd='';
           this.isLogin=false;
          }


        });
      },
      login:function (){
        var params=new URLSearchParams();
        params.append("username",this.username);
        params.append("pwd",this.pwd);
        params.append("valcode",this.valcode);
        axios.post('user.action?op=login',params).then(result=>{
          let jm=result.data;
          if (jm.code==0){
            alert("登录失败原因是"+result.msg);
            return;
          }
          this.username=jm.obj.username;
          console.log(this.username);
          this.loginflag=false;
          this.isLogin=true;

        });
      },
      checkLogin:function (){
        //get的结果是一个promise对象
        return axios.get('user.action?op=checkLogin')
      },
      findAllFoods:function (){
        //get的结果是一个promise对象
        return axios.get('resfood.action?op=findAllFoods')
      },
      showCartInit:function (){
        axios.post('resorder.action?op=getCartInfo').then(result=>{
          let jm=result.data;
          if (jm.code==1){
            this.showCartInfo(jm.obj);
          }
        });
      },
      clickPage:function (pageno){
        var promise=this.showPage(pageno);
       promise.then(result=>{
         this.displayPage(result.data);
               }

       );
      },
      showPage:function (pageno){
        var params=new URLSearchParams();
        params.append("pageno",pageno);
        params.append("sortby",this.pagebean.sortby);
        params.append("sort",this.pagebean.sort);
        return axios.post("resfood.action?op=findFoodsByPage",params);
      },
      displayPage:function (result){
        let jsonModel2=result;
        if (jsonModel2.code==1){
          jsonModel2.obj.dataset.forEach((item,index)=>{
            item.status=false;//给每个菜品添加一个属性，用来判断菜品是隐藏还是显示。
          });
          vm.$data.data = jsonModel2.obj.dataset;//菜品列表的数据。
          vm.$data.pagebean=jsonModel2.obj;

        }
      },
      //获取历史记录
      getHistory:function (){
        axios.post('resfood.action?op=getHistory').then(result=>{
          let jm=result.data;
          this.history=[];
          if (jm.code==1){
            this.history=jm.obj;
          }
        });
      }
    },
    computed:{
      reversehistory(){//引入属性，将历史记录倒序输出
        return this.history.reverse();
      }
    },
    mounted:function (){
      //分页时将this.findAllFoods()改成showPage()
      axios.all([this.checkLogin(), this.showPage(1),this.showCartInit(),this.getHistory()]).then(
              axios.spread((d1, d2) => {
                if (d1.data.code == 1) {
                  // vm.$data指的是view-model中的数据
                  // this.username:这是view-model中的数据
                  vm.$data.username = d1.data.obj.username;
                  vm.$data.isLogin = true;
                  vm.$data.loginflag = false;
                }
                let jsonModel2=d2.data;
                if (jsonModel2.code == 1) {
                  // 显示数据到页面
                  vm.displayPage(jsonModel2);
                }
              })
      );

    }
  });
</script>

</body>
</html>